import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import re

def html_parser(url):

    res = requests.get(url)
    if res.status_code != 200:
        print("error")
    res.encoding = 'utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    return soup,url,res

url = 'https://www.msn.cn/zh-cn/weather/forecast/in-%E6%B2%B3%E5%8D%97%E7%9C%81,%E6%96%B0%E4%B9%A1%E5%B8%82?ocid=ansmsnweather&loc=eyJsIjoi5paw5Lmh5Y6%2FIiwiciI6Iuays%2BWNl%2BecgSIsInIyIjoi5paw5Lmh5biCIiwiYyI6IuS4reWNjuS6uuawkeWFseWSjOWbvSIsImkiOiJjbiIsInQiOjEwMiwiZyI6InpoLWNuIiwieCI6IjExMy44MTM3Njk0IiwieSI6IjM1LjE3MDU1OTYifQ%3D%3D&weadegreetype=C'
soup,url,res=html_parser(url)

#title = soup.title.string
# patter = re.compile('<g class="tempLabels-E1_1">(.*?)</g>', re.S)
# temp = patter.findall(res.text)
#print(type(temp))
# temp_soup=BeautifulSoup(temp,'html.parser')
# print(temp_soup)

links = soup.find_all('text')[0:13]
x=[]
y=[]
temp_temp=[]
for link in links:
    temp_x = link.get('x')
    temp_x = temp_x[:-1]
    temp_x = temp_x[:4]
    x.append(float(temp_x))

    temp_y = link.get('y')
    temp_y = temp_y[:-1]
    temp_y = temp_y[:4]
    y.append(40-float(temp_y))

    wd = link.get_text()
    temp_temp.append(wd)
    #print(temp_x, temp_y,wd[:-1])

times=[]
links = soup.find_all('text')[13:26]
for link in links:
    tm = link.get_text()
    times.append(tm)

plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
plt.figure(figsize=(20,5),dpi=100)
x1=[0,100]
y1=[4.9,4.9]
plt.title("新乡市气温")
plt.plot(x,y)
plt.plot(x1,y1)
x_sticks=["{}".format(i) for i in times]

plt.xticks(x[::1],x_sticks[::1])
y_sticks=range(30)
plt.yticks(y_sticks[::1])
for i in range(len(temp_temp)):
    plt.text(x[i], y[i], temp_temp[i], ha='center', va='bottom', fontsize=20)
plt.show()
